<!DOCTYPE html>
<html>
<head>
    <title>页面wangEditor新增</title>
    {% include 'system/common/header.html' %}</head>
    <link rel="stylesheet" href="{{ url_for('admin.static', filename='system/component/wangeditor/style.css') }}"/>
    <style>

    </style>
<body>
<form class="layui-form" action="">
    <input type="hidden" name="type" id="article-type" value="wangEditor">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">页面名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="页面名称"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">页面别名</label>
                    <div class="layui-input-block">
                        <input type="text" name="slug" lay-verify="required" autocomplete="off" placeholder="别名"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">页面摘要</label>
                    <div class="layui-input-block">
                        <textarea placeholder="页面摘要" name="excerpt" class="layui-textarea"></textarea>
                    </div>
                </div>
                
                <!-- 特色图像 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">特色图像</label>
                    <div class="layui-input-block">
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <input type="text" name="featured_image" id="featured-image-url" placeholder="请输入图片地址或上传图片" class="layui-input">
                            </div>
                            <div class="layui-col-md6">
                                <button type="button" class="layui-btn layui-btn-primary" id="upload-featured-image">
                                    <i class="layui-icon layui-icon-upload"></i> 上传图片
                                </button>
                                <button type="button" class="layui-btn layui-btn-normal" id="paste-image-url">
                                    <i class="layui-icon layui-icon-link"></i> 粘贴地址
                                </button>
                            </div>
                        </div>
                        <div id="featured-image-preview" style="margin-top: 10px; display: none;">
                            <img id="preview-img" src="" alt="特色图像预览" style="max-width: 300px; max-height: 200px; border: 1px solid #e6e6e6; border-radius: 2px;">
                            <div style="margin-top: 5px;">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="remove-featured-image">
                                    <i class="layui-icon layui-icon-close"></i> 移除图片
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item layui-form-text">
                    <div class="layui-form-label">页面内容</div>
                    <div id="editor-wrapper">
                      <div id="toolbar-container"><!-- 工具栏 --></div>
                      <div id="editor-container"><!-- 编辑器 --></div>
                      <textarea name="content" id="editor-content" style="display: none;"></textarea>
                    </div>
                </div>
                
                <!-- SEO信息 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_title" placeholder="SEO标题（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">SEO关键词</label>
                    <div class="layui-input-block">
                        <input type="text" name="meta_keywords" placeholder="SEO关键词，多个关键词用逗号分隔（可选）" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">SEO描述</label>
                    <div class="layui-input-block">
                        <textarea name="meta_description" placeholder="SEO描述（可选）" class="layui-textarea" style="height: 80px;"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="page-save">
                <i class="layui-icon layui-icon-ok"></i>
                草稿
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="publish-btn">
                <i class="layui-icon layui-icon-release"></i>
                发布
            </button>
        </div>
    </div>
</form>
{% include 'system/common/footer.html' %}
<style>
#editor-wrapper {
    border: 1px solid #ccc;
    margin-left: 110px;
    z-index: 100; /* 按需定义 */
}
#toolbar-container {
    border-bottom: 1px solid #ccc;
}
#editor-container {
    height: 500px;
}
</style>

<!-- 全局变量 -->
<script>
let editor = null; // 全局编辑器实例
</script>

<!-- 加载wangEditor -->
<script src="{{ url_for('admin.static', filename='system/component/wangeditor/index.js') }}"></script>

<script>
// 初始化wangEditor
document.addEventListener('DOMContentLoaded', function() {
    console.log('开始初始化wangEditor...');
    
    // 检查wangEditor是否加载
    if (typeof window.wangEditor === 'undefined') {
        console.error('wangEditor未加载');
        return;
    }
    
    const { createEditor, createToolbar } = window.wangEditor;
    
    if (!createEditor || !createToolbar) {
        console.error('wangEditor API未正确加载');
        return;
    }
    
    console.log('wangEditor API加载成功');
    
    // 编辑器配置
    const editorConfig = {
        placeholder: '请输入页面内容...',
        onChange(editor) {
            const html = editor.getHtml();
            console.log('编辑器内容变化:', html);
            // 同步到隐藏的textarea
            document.getElementById('editor-content').value = html;
        },
        // 图片上传配置
        MENU_CONF: {
            uploadImage: {
                server: '/admin/cms/post/upload',
                fieldName: 'image',
                maxFileSize: 10 * 1024 * 1024, // 10MB
                maxNumberOfFiles: 10,
                allowedFileTypes: ['image/*'],
                meta: {
                    type: 'images'
                },
                metaWithUrl: true,
                withCredentials: false,
                timeout: 5 * 1000, // 5s
                // 自定义响应处理
                customInsert(res, insertFn) {
                    console.log('自定义插入图片:', res);
                    if (res.errorCode === 0) {
                        insertFn(res.data.src, res.data.alt, res.data.src);
                    }
                },
                onBeforeUpload(file) {
                    console.log('图片上传开始:', file.name);
                    return file;
                },
                onProgress(progress) {
                    console.log('图片上传进度:', progress);
                },
                onSuccess(file, res) {
                    console.log('图片上传成功:', res);
                    if (res.errorCode === 0) {
                        // 返回图片URL，wangEditor会自动插入
                        console.log('返回图片URL:', res.data.src);
                        // 返回完整的响应数据，让wangEditor自己处理
                        return res;
                    } else {
                        console.error('图片上传失败:', res);
                        return false;
                    }
                },
                onFailed(file, res) {
                    console.error('图片上传失败:', res);
                    layer.msg('图片上传失败: ' + (res.msg || '未知错误'), {icon: 2});
                },
                onError(file, err, res) {
                    console.error('图片上传错误:', err);
                    layer.msg('图片上传错误: ' + err.message, {icon: 2});
                }
            },
            uploadVideo: {
                server: '/admin/cms/post/upload',
                fieldName: 'video',
                maxFileSize: 500 * 1024 * 1024, // 500MB，与服务器配置一致
                maxNumberOfFiles: 5,
                allowedFileTypes: ['video/*'],
                meta: {
                    type: 'video'
                },
                metaWithUrl: true,
                withCredentials: false,
                timeout: 60 * 1000, // 60s
                // 自定义响应处理
                customInsert(res, insertFn) {
                    console.log('自定义插入视频:', res);
                    if (res.errorCode === 0) {
                        insertFn(res.data.src, res.data.alt, res.data.src);
                    }
                },
                onBeforeUpload(file) {
                    console.log('视频上传开始:', file.name);
                    return file;
                },
                onProgress(progress) {
                    console.log('视频上传进度:', progress);
                },
                onSuccess(file, res) {
                    console.log('视频上传成功:', res);
                    if (res.errorCode === 0) {
                        // 返回视频URL，wangEditor会自动插入
                        console.log('返回视频URL:', res.data.src);
                        // 返回完整的响应数据，让wangEditor自己处理
                        return res;
                    } else {
                        console.error('视频上传失败:', res);
                        return false;
                    }
                },
                onFailed(file, res) {
                    console.error('视频上传失败:', res);
                    layer.msg('视频上传失败: ' + (res.msg || '未知错误'), {icon: 2});
                },
                onError(file, err, res) {
                    console.error('视频上传错误:', err);
                    layer.msg('视频上传错误: ' + err.message, {icon: 2});
                },
                insertImage: {
                    checkImage: true,
                    parseImageSrc: (src) => {
                        console.log('解析图片链接:', src);
                        return src;
                    },
                    onInsertedImage: (imageNode) => {
                        console.log('图片插入成功:', imageNode);
                    }
                },
                insertVideo: {
                    checkVideo: true,
                    parseVideoSrc: (src) => {
                        console.log('解析视频链接:', src);
                        return src;
                    },
                    onInsertedVideo: (videoNode) => {
                        console.log('视频插入成功:', videoNode);
                    }
                }
            }
        }
    };
    
    // 创建编辑器
    try {
        editor = createEditor({
            selector: '#editor-container',
            html: '<p><br></p>',
            config: editorConfig,
            mode: 'default',
        });
        
        console.log('编辑器创建成功:', editor);
        
        // 创建工具栏
        const toolbarConfig = {
            toolbarKeys: [
                'headerSelect',
                'bold',
                'italic',
                'underline',
                'through',
                '|',
                'color',
                'bgColor',
                '|',
                'fontSize',
                'fontFamily',
                'lineHeight',
                '|',
                'bulletedList',
                'numberedList',
                'todo',
                '|',
                'justifyLeft',
                'justifyRight',
                'justifyCenter',
                'justifyJustify',
                '|',
                'emotion',
                'insertLink',
                'uploadImage',
                'insertImage',  // 通过链接插入图片
                'uploadVideo',
                'insertVideo',  // 通过链接插入视频
                'insertTable',
                'codeBlock',
                'divider',
                '|',
                'undo',
                'redo',
                '|',
                'fullScreen'
            ]
        };
        const toolbar = createToolbar({
            editor,
            selector: '#toolbar-container',
            config: toolbarConfig,
            mode: 'default',
        });
        
        console.log('工具栏创建成功:', toolbar);
        
        // 将编辑器实例设为全局变量
        window.editor = editor;

    } catch (error) {
        console.error('编辑器初始化失败:', error);
    }
});

// 获取编辑器内容的函数
function getEditorContent() {
    let content = '';
    
    // 方法1: 使用编辑器API
    if (editor && typeof editor.getHtml === 'function') {
        content = editor.getHtml();
        console.log('从编辑器API获取内容:', content);
        return content;
    }
    
    // 方法2: 从隐藏的textarea获取
    const textarea = document.getElementById('editor-content');
    if (textarea && textarea.value) {
        content = textarea.value;
        console.log('从textarea获取内容:', content);
        return content;
    }
    
    // 方法3: 从DOM获取
    const editorElement = document.querySelector('#editor-container');
    if (editorElement) {
        const contentElement = editorElement.querySelector('[contenteditable="true"]') ||
                              editorElement.querySelector('.w-e-text') ||
                              editorElement;
        
        if (contentElement) {
            content = contentElement.innerHTML;
            console.log('从DOM获取内容:', content);
            return content;
        }
    }
    
    console.warn('无法获取编辑器内容');
    return '';
}

// 特色图像功能
layui.use(['form', 'jquery'], function() {
    let $ = layui.jquery;
    
    // 上传图片
    $('#upload-featured-image').click(function() {
        // 创建一个隐藏的文件输入框
        let fileInput = $('<input type="file" accept="image/*" style="display: none;">');
        $('body').append(fileInput);
        
        fileInput.click();
        
        fileInput.on('change', function() {
            let file = this.files[0];
            if (file) {
                // 创建FormData对象
                let formData = new FormData();
                formData.append('image', file);
                formData.append('type', 'images');
                
                // 上传文件
                $.ajax({
                    url: '/admin/cms/page/upload',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(result) {
                        if (result.errorCode === 0) {
                            let imageUrl = result.data.src;
                            $('#featured-image-url').val(imageUrl);
                            showImagePreview(imageUrl);
                            layer.msg('图片上传成功', {icon: 1});
                        } else {
                            layer.msg(result.msg || '上传失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('上传失败', {icon: 2});
                    }
                });
            }
            
            // 移除临时文件输入框
            fileInput.remove();
        });
    });
    
    // 粘贴图片地址
    $('#paste-image-url').click(function() {
        layer.prompt({
            title: '请输入图片地址',
            formType: 0,
            value: '',
            area: ['400px', '150px']
        }, function(value, index) {
            if (value && value.trim()) {
                $('#featured-image-url').val(value.trim());
                showImagePreview(value.trim());
                layer.close(index);
                layer.msg('图片地址已设置', {icon: 1});
            } else {
                layer.msg('请输入有效的图片地址', {icon: 2});
            }
        });
    });
    
    // 移除特色图像
    $('#remove-featured-image').click(function() {
        $('#featured-image-url').val('');
        $('#featured-image-preview').hide();
        layer.msg('特色图像已移除', {icon: 1});
    });
    
    // 显示图片预览
    function showImagePreview(imageUrl) {
        if (imageUrl && imageUrl.trim()) {
            $('#preview-img').attr('src', imageUrl);
            $('#featured-image-preview').show();
        } else {
            $('#featured-image-preview').hide();
        }
    }
    
    // 监听图片地址输入框变化
    $('#featured-image-url').on('input', function() {
        let imageUrl = $(this).val().trim();
        showImagePreview(imageUrl);
    });
    
    // 初始化特色图像预览（如果有值）
    let initialImageUrl = $('#featured-image-url').val();
    if (initialImageUrl) {
        showImagePreview(initialImageUrl);
    }
});

// 表单提交处理
layui.use(['form', 'jquery'], function () {
    let form = layui.form
    let $ = layui.jquery
    
    console.log('Layui form 初始化完成');

    // 获取URL参数并设置页面类型
    function getUrlParameter(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
      var results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }
    
    // 设置页面类型
    var articleType = getUrlParameter('type') || 'wangEditor';
    $('#article-type').val(articleType);
    console.log('页面类型:', articleType);

    // 草稿按钮事件处理
    form.on('submit(page-save)', function (data) {
      console.log('草稿按钮事件触发', data);
      
      // 获取编辑器内容
      let editorContent = getEditorContent();
      
      // 构建提交数据
      let submitData = {
        title: data.field.title,
        slug: data.field.slug,
        excerpt: data.field.excerpt,
        featured_image: data.field.featured_image || '',
        content: editorContent,
        meta_title: data.field.meta_title || '',
        meta_keywords: data.field.meta_keywords || '',
        meta_description: data.field.meta_description || '',
        type: 'wangEditor',
        status: 'draft'
      }
      
      console.log('准备提交的数据:', submitData);
      console.log('提交URL:', '/admin/cms/page/save');
      
      $.ajax({
        url: '/admin/cms/page/save',
        data: JSON.stringify(submitData),
        dataType: 'json',
        contentType: 'application/json',
        type: 'post',
        success: function (result) {
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
              parent.layer.close(parent.layer.getFrameIndex(window.name))
              parent.layui.table.reload('page-table')
            })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
          }
        },
        error: function (xhr, status, error) {
          layer.msg('保存失败: ' + error, { icon: 2, time: 2000 })
        }
      })
      return false
    })
    
    // 发布按钮事件处理
    $('#publish-btn').click(function() {
      console.log('发布按钮事件触发');
      
      // 获取表单数据
      let formData = {};
      $('form.layui-form input, form.layui-form textarea, form.layui-form select').each(function() {
        let name = $(this).attr('name');
        let value = $(this).val();
        if (name) {
          formData[name] = value;
        }
      });
      
      console.log('获取到的表单数据:', formData);
      
      // 获取编辑器内容
      let editorContent = getEditorContent();
      
      // 构建提交数据
      let submitData = {
        title: formData.title,
        slug: formData.slug,
        excerpt: formData.excerpt,
        featured_image: formData.featured_image || '',
        content: editorContent,
        meta_title: formData.meta_title || '',
        meta_keywords: formData.meta_keywords || '',
        meta_description: formData.meta_description || '',
        type: 'wangEditor',
        status: 'published'
      }
      
      console.log('准备发布的数据:', submitData);
      console.log('发布URL:', '/admin/cms/page/save');
      
      $.ajax({
        url: '/admin/cms/page/save',
        data: JSON.stringify(submitData),
        dataType: 'json',
        contentType: 'application/json',
        type: 'post',
        success: function (result) {
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
              parent.layer.close(parent.layer.getFrameIndex(window.name))
              parent.layui.table.reload('page-table')
            })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
          }
        },
        error: function (xhr, status, error) {
          layer.msg('发布失败: ' + error, { icon: 2, time: 2000 })
        }
      })
    })
})
</script>

</body>
</html> 